<template>
  <el-row class="user-info-form" type="flex" justify="center">
    <el-col>
      <div class="asset-info-form">
        <el-form label-width="150px" :model="fireCarBaseInfoForm" :rules="fireCarBaseInfoFormRules" ref="fireCarBaseInfoForm" @submit.native.prevent>
          <el-form-item label="联网单位：" prop='orgId'>
            <el-select filterable v-model="fireCarBaseInfoForm.orgId">
              <el-option
                v-for="item in orgList"
                :key="item.organizationId"
                :label="item.shortName"
                :value="item.organizationId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="名称："  prop='name'>
            <el-input
              v-model="fireCarBaseInfoForm.name"
              clearable>
            </el-input>
          </el-form-item>
          <el-form-item label="车牌号："  prop='carNumber'>
            <el-input
              v-model="fireCarBaseInfoForm.carNumber"
              clearable>
            </el-input>
          </el-form-item>
          <el-form-item label="车辆类型："  prop='carType'>
            <el-select v-model="fireCarBaseInfoForm.carType">
              <el-option
                v-for="item in carTypeList"
                :key="parseInt(item.dictKey)"
                :label="item.dictValue"
                :value="parseInt(item.dictKey)">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="服务平台："  prop='serverPlat'>
            <el-select v-model="fireCarBaseInfoForm.serverPlat">
              <el-option
                v-for="item in serverPlatList"
                :key="parseInt(item.dictKey)"
                :label="item.dictValue"
                :value="parseInt(item.dictKey)">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="定位标识："  prop='bizId'>
            <el-input
              v-model="fireCarBaseInfoForm.bizId"
              clearable>
            </el-input>
          </el-form-item>
          <el-form-item label="车辆介绍："  prop='carDescribe'>
            <el-input type="textarea"  style="min-height: 100px;"
              v-model="fireCarBaseInfoForm.carDescribe"
              clearable>
            </el-input>
          </el-form-item>
          <el-form-item label="图片：" prop='pictures'>
            <el-upload
              :action="QINIUUPLOADURL"
              :multiple="false"
              ref="upload"
              list-type="picture-card"
              :data="qiniuData"
              :on-success="handleAvatarSuccess"
              :on-remove="handleRemovePic"
              :on-error="handleError"
              :before-upload="beforeAvatarUpload"
              :on-preview="$imgPreview"
              :file-list="qiniuData.fileList"
              :limit="3"
              :on-exceed="handleExceed"
              accept="image/gif,image/jpeg,image/jpg,image/bmp,image/png">
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label-width="0" class="verifyidentity-button">
            <el-button @click.stop="closeFun(false)" round>取消</el-button>
            <el-button type="primary" @click="saveFireCarInfo('fireCarBaseInfoForm')" round>保存</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-col>
  </el-row>
</template>
<script>
import { qnToken} from '@/api/api'
import util from '@/utils/util'
import { getDictByCode } from '@/api/dic'
import { saveOrUpdateCarInfo } from '@/api/sysConfig'
export default {
    name: 'GridManageBaseInfo',
    props: {
      fireCarInfo: {
        type: Object
      },
      orgList: {
         type: Array
      },

      closeFun: {
        type: Function,
        required: true
      },
    },
    data(){
      return {
        carTypeList: [],
        serverPlatList: [],
        qiniuData:{//上传图片携带的参数
          token : "",
          key : "",
          fileList:[],
        },

        // 表单数据
        fireCarBaseInfoForm: {
          id: '',
          orgId: '',
          name: '',
          carNumber: '',
          carTypeName: '',
          carType: '',
          serverPlat: '',
          bizId: '',
          carDescribe: ''
        },
        // 表单校验
        fireCarBaseInfoFormRules: {
          orgId: [
            { required: true, message: '请选择联网单位', trigger: 'change' }
          ],
          name: [
            { required: true, message: '请输入名称', trigger: 'blur' }
          ],
          carNumber: [
            { required: true, message: '请输入车牌号', trigger: 'blur' }
          ],
          carType: [
            { required: true, message: '请选择车辆类型', trigger: 'change' }
          ],
          serverPlat: [
            { required: true, message: '请选择服务平台', trigger: 'change' }
          ],
          bizId: [
            { required: true, message: '请输入定位标识', trigger: 'blur' }
          ]
        }
      }
    },
    created() {
      let that = this
      that.getToken()
      // 如果有历史值，设置回显
      if(that.fireCarInfo.id) {
        for(let key in that.fireCarBaseInfoForm) {
          that.fireCarBaseInfoForm[key] = that.fireCarInfo[key]
        }

        // 设置上传图片初始值
        that.fireCarInfo.pictureUrl ? $.each(that.fireCarInfo.pictureUrl.split(','), (index,url) => {
          that.qiniuData.fileList.push({
            name: that.fireCarInfo.id + index,
            url:url
          })
        }) : ''
      }

      // 获取车辆类型数据
      getDictByCode({
          code: 45
      }).then(res => {
        if(res.status = 200) {
           that.carTypeList = res.data.dictValueObj
        }
      })
      // 获取服务平台数据
      getDictByCode({
          code: 114
      }).then(res => {
        if(res.status = 200) {
           that.serverPlatList = res.data.dictValueObj
        }
      })
    },
    methods: {
      getToken(){  //上传之前获取 token
        qnToken({}).then((result) => {
          this.qiniuData.token= result.data
        })
      },
      beforeAvatarUpload: function(file){//重命名和校验
        var fielLocal = file.name.split(".")
        var fielType = "." + fielLocal[fielLocal.length-1]
        var fielLocalName = fielLocal[0]
        this.qiniuData.key = 'assesImg'+'_'+new Date().getTime()+fielType
        //this.qiniuData.key = file.name;
        const isJPG = file.type === "image/jpeg";
        const isPNG = file.type === "image/png";
        const isLt20M = file.size / 1024 / 1024 < 20;
        if (!isJPG && !isPNG) {
          this.$message.error("图片只能是 JPG/PNG 格式!")
          return false;
        }
        if (!isLt20M) {
          this.$message.error("图片大小不能超过 20MB!")
          return false;
        }
      },
      handleAvatarSuccess: function(res, file, fileList) {//上传成功
        this.qiniuData.fileList = fileList
      },
      handleRemovePic: function(file, fileList) {//删除成功
        this.qiniuData.fileList = fileList
      },
      handleError: function(res) {
        this.$message({
          message: "上传失败",
          duration: 2000,
          type: "warning"
        })
      },
      handleExceed(files, fileList) {//文件超出个数限制时的钩子
        this.$message.warning(`只能上传3张图片！`)
      },

      // 保存
      saveFireCarInfo(formName) {
        // 阻止事件冒泡
        event.stopPropagation()
        let that = this
        let type = 1
        let parames = {}
        // 校验表单
        that.$refs[formName].validate((valid) => {
          if(valid) {
            var parames = {
              bizId : that.fireCarBaseInfoForm.bizId,
              name: that.fireCarBaseInfoForm.name,
              carNumber : that.fireCarBaseInfoForm.carNumber,
              carType : that.fireCarBaseInfoForm.carType,
              serverPlat: that.fireCarBaseInfoForm.serverPlat,
              orgId: that.fireCarBaseInfoForm.orgId,
              carDescribe: that.fireCarBaseInfoForm.carDescribe,
              pictureUrl: util.ilinkArrHandle.getqiniuPicUrlArr(that.qiniuData.fileList).toString(),
              id: that.fireCarInfo.id
            }
            if(that.fireCarInfo.id==null || that.fireCarInfo.id==""){
                parames.id = 0
            }
            // 调用保存接口
            saveOrUpdateCarInfo(parames).then(res => {
              if(res.status === 200) {
                that.$message({
                  message: '保存成功！',
                  type: 'success'
                })
                // 关闭弹框
                that.closeFun(true)
              } else {
                that.$message({
                  message: '保存失败！',
                  type: 'warning'
                })
              }
            })
          } else {
            return false
          }
        })
      }
    }
  }
</script>
